package controller

import (
	"frontend-server/dao"
	model "frontend-server/model/gv_im"
	"frontend-server/util"
	"log"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}
var wc = make(map[uint]*websocket.Conn)

type MessageStruct struct {
	RoomID  uint   `json:"room_id"`
	Message string `json:"message"`
	Type    int    `json:"type"`
}

type WebsocketController struct{}

func (WebsocketController) Init(ctx *gin.Context) {
	// 升级为 websocket
	conn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		util.Fail(ctx, util.R{
			P: util.P{
				Code:    500,
				Message: "系统错误: " + err.Error(),
			},
		})
		return
	}
	defer conn.Close()
	userID := ctx.MustGet("id").(uint)
	wc[userID] = conn
	for {
		ms := new(MessageStruct)
		err := conn.ReadJSON(ms)
		if err != nil {
			log.Printf("Read Error: %v", err)
			return
		}
		// 判断用户是否属于消息体房间
		_, err = dao.GetGvImUserRoomByUserIDRoomID(userID, ms.RoomID)
		if err != nil {
			log.Printf("UserID:%v RoomID:%v not exits\n", userID, ms.RoomID)
		}
		// 保存消息
		mb := model.GvImMessage{
			UserID: userID,
			RoomID: ms.RoomID,
			Data:   ms.Message,
			Type:   ms.Type,
		}
		err = dao.CreateGvImMessage(mb)
		if err != nil {
			log.Printf("[DB ERROR]:%v", err)
			return
		}
		// 获取在特定房间的用户
		userRooms, err := dao.GetGvImUserRoomByRoomID(ms.RoomID)
		if err != nil {
			log.Printf("[DB ERROR]:%v\n", err)
			return
		}
		for _, userRoom := range userRooms {
			if cc, ok := wc[userRoom.UserID]; ok {
				err := cc.WriteMessage(websocket.TextMessage, []byte(ms.Message))
				if err != nil {
					log.Printf("Write Message Error: %v", err)
					return
				}
			}
		}
	}
}
